const router = require('koa-router')()
const jwt = require('jsonwebtoken');
const { Worker } = require('worker_threads')

router.prefix('/timefarm')

/**
 * 上传params+proxy
 * 会清空之前的设定
 */
router.post('/setup', async (ctx, next) => {
    const conn = ctx.state.sqlconn;
    const tableData = ctx.request.body;
    try {
        await conn.beginTransaction();
        await conn.query('delete from timefarm where id>0')
        for (let index = 0; index < tableData.length; index++) {
            const element = tableData[index];
            await conn.query('insert into timefarm (phone, params, proxy) values (?, ?, ?)', [element.phone, element.params, element.proxy]);
        }
        await conn.commit();
        const [results, fields] = await conn.query('select * from timefarm');
        ctx.body = {
            code: 200,
            msg: 'ok',
            data: results
        }
    } catch (error) {
        console.error(error)
        await conn.rollback();
        ctx.body = {
            code: -1,
            msg: '事务失败，已回滚',
            data: error
        }
    }
})

router.post('/token', async (ctx, next) => {
    const conn = ctx.state.sqlconn;
    const body = ctx.request.body;
    try {
        let queryId = body.params
        queryId = decodeURIComponent(queryId)
        const leftIndex = queryId.indexOf('{')
        const rightIndex = queryId.indexOf('}')
        const userStr = queryId.substring(leftIndex, rightIndex + 1)
        const userDic = JSON.parse(userStr)
        const userId = userDic["id"]
        await conn.query(`insert into timefarm (user_id, params) values (?, ?)
            on duplicate key
            update params=?`, [userId, queryId, queryId])
        ctx.body = {
            code: 200,
            msg: "ok"
        }
    } catch (error) {
        console.error(error)
        ctx.body = {
            code: -1,
            msg: '更新token失败',
            data: error
        }
    }
})

router.get('/setup', async (ctx, next) => {
    const conn = ctx.state.sqlconn;
    const [results, fields] = await conn.query('select * from timefarm where id>0')
    ctx.body = {
        code: 200,
        msg: 'ok',
        data: results
    }
})

router.post('/excute', async (ctx, next) => {
    const excutor = TimefarmExcutor.shared()
    excutor.start()
    ctx.body = {
        code: 200,
        msg: 'ok',
        data: excutor.isRunning()
    }
})

router.get('/excute', async (ctx, next) => {
    const excutor = TimefarmExcutor.shared()
    ctx.body = {
        code: 200,
        msg: 'ok',
        data: excutor.isRunning()
    }
})

module.exports = router


// worker thread
class TimefarmExcutor {
    constructor() {}

    static shared() {
        if (!TimefarmExcutor.instance) {
            TimefarmExcutor.instance = new TimefarmExcutor();
        }
        return TimefarmExcutor.instance;
    }

    start() {
        if (this.worker != null) {
            return;
        }
        const worker = new Worker("./worker/timefarm.js", {
            workerData: "hello world"
        });
        // worker.on('message', (msg) => {
        //     console.log(msg)
        // });
        worker.on('error', (error) => {
            console.error(error)
        });
        worker.on('exit', (code) => {
            console.log("worker exit: ", code)
            this.worker = null
        });
        this.worker = worker
    }

    stop() {
        if (this.worker != null) {
            this.worker.terminate()
        }
    }

    isRunning() {
        return this.worker != null
    }
}